package com.stormragetech.sylwanas.converter;

import com.alibaba.fastjson.JSON;
import com.stormragetech.sylwanas.common.MessageWrapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.util.UUID;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class FastjsonMessageConverter<T> implements MessageConverter {

    private final static String DEFAULT_CHARSET = "UTF-8";

    @Override
    @SuppressWarnings("unchecked")
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        MessageWrapper wrapper = (MessageWrapper) object;
        return createMessage(wrapper, messageProperties);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object fromMessage(Message message) throws MessageConversionException {

        try {

            String json = new String(message.getBody(), message.getMessageProperties().getContentEncoding());
            return JSON.parseObject(json, (Class<T>) Class.forName(message.getMessageProperties().getType()));
        } catch (Exception e) {
            throw new MessageConversionException("Failed to convert Message content", e);
        }
    }

    @SuppressWarnings("unchecked")
    private Message createMessage(MessageWrapper wrapper, MessageProperties messageProperties) {

        if (null == messageProperties) {
            messageProperties = new MessageProperties();
        }

        try {
            T t = (T) wrapper.getMessage();
            String json = JSON.toJSONString(t);
            byte[] bytes = json.getBytes(DEFAULT_CHARSET);

            messageProperties.setMessageId(wrapper.getId());
            messageProperties.setType(t.getClass().getName());
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            messageProperties.setContentEncoding(DEFAULT_CHARSET);
            messageProperties.setContentLength((long) bytes.length);
//            if (null == messageProperties.getMessageId()) {
//                messageProperties.setMessageId(UUID.randomUUID().toString());
//            }

            return new Message(bytes, messageProperties);

        } catch (Exception e) {
            throw new MessageConversionException("Failed to convert Message content", e);
        }
    }

}
